import 'package:cached_network_image/cached_network_image.dart';
import 'package:flukit/flukit.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_app/2_advance/common/app_color.dart';
import 'package:flutter_app/2_advance/common/app_style.dart';
import 'package:flutter_app/2_advance/common/no_scroll_behavi_widget.dart';
import 'package:flutter_app/2_advance/net/app_request.dart';
import 'package:flutter_app/generated/assets.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

class ReadPage extends StatefulWidget {
  const ReadPage({Key? key}) : super(key: key);

  @override
  State<ReadPage> createState() => _ReadPageState();
}

class _ReadPageState extends State<ReadPage> {

  RefreshController _refreshController = RefreshController(initialRefresh: true);

  List<String> _imageList = [];

  @override
  void initState() {
    print('ReadPage initState');
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: AppColor.appBackground,
      body: SafeArea(
        child: ScrollConfiguration(
          behavior: NoScrollBehaviorWidget(),
          // SmartRefresh 的child一定得是可滑动组件
          child: SmartRefresher(
            controller: _refreshController,
            onRefresh: () async {
              // monitor network fetch
              await Future.delayed(Duration(milliseconds: 1000));
              List<String>? imageList = await AppRequest.getRecommendImages();
              setState(() => _imageList = imageList);
              // if failed,use refreshFailed()
              _refreshController.refreshCompleted();
            },
            child: ListView(
              padding: EdgeInsets.only(bottom: MediaQuery.of(context).padding.bottom),
              shrinkWrap: true,
              children: [
                  Padding(
                    padding: const EdgeInsets.fromLTRB(16, 12, 16, 16),
                    child: SearchView(
                      onNavBookCity: () {
                        print('跳转到书城');
                      },
                    ),
                  ),
                  BookClassifyView(
                    titleList: ['分类', '榜单', '书单', '免费', '男生', '女生'],
                    onTap: (index) {
                      print('您点击了 $index');
                    },
                  ),
                  Padding(
                    padding: const EdgeInsets.symmetric(vertical: 16),
                    child: BookRecordView(),
                  ),
                  const SizedBox(height: 16),
                  RecommendView(imageList: _imageList),
                  const SizedBox(height: 16),
                  DailyWelfareView(),
                ],
              ),
          ),
          ),
        ),
    );
  }
}

class SearchView extends StatelessWidget {
  const SearchView({Key? key, required this.onNavBookCity}) : super(key: key);

  final VoidCallback onNavBookCity;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(100),
        color: Color(0xffe3e2e2),
      ),
      child: Row(
        children: [
          Icon(Icons.search, color: Colors.grey, size: 20),
          const SizedBox(width: 8),
          Expanded(child: Text('弹子球游戏原著', style: TextStyle(color: Colors.grey))),
          SizedBox(height: 18, child: VerticalDivider(width: 1, color: Colors.grey)),
          CupertinoButton(
            child: Text(
              '书城',
              style: TextStyle(fontSize: 14, color: Color(0xFF5f646e)),
            ),
            onPressed: onNavBookCity,
            minSize: 0,
            padding: EdgeInsets.symmetric(vertical: 10, horizontal: 8),
          ),
        ],
      ),
    );
  }
}

/// 书籍分类
class BookClassifyView extends StatelessWidget {
  const BookClassifyView({Key? key, required this.titleList, required this.onTap})
      : super(key: key);

  final List<String> titleList;

  final ValueChanged<int> onTap;

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: List.generate(titleList.length + 1, (index) {
          if (index == 0) return SizedBox(width: 16);
          return GestureDetector(
            onTap: () => onTap(index),
            child: Container(
              decoration: BoxDecoration(
                color: Color(0xFFededed),
                borderRadius: BorderRadius.circular(100),
              ),
              padding: EdgeInsets.fromLTRB(16, 8, 12, 8),
              margin: EdgeInsets.only(right: 8),
              child: Row(
                children: [
                  Text(titleList[index - 1],
                      style: TextStyle(color: Color(0xFF81848c), fontWeight: FontWeight.w600)),
                  Icon(Icons.arrow_forward_ios, size: 12, color: Colors.black38),
                ],
              ),
            ),
          );
        }),
      ),
    );
  }
}

const List<String> _bookImages = [
  Assets.imageBook1,
  Assets.imageBook2,
  Assets.imageBook3,
  Assets.imageBook4,
  Assets.imageBook5,
];

/// 阅读记录
class BookRecordView extends StatelessWidget {
  const BookRecordView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return SingleChildScrollView(
      scrollDirection: Axis.horizontal,
      child: Row(
        children: [
          const SizedBox(width: 16),
          _readTimeCard(),
          const SizedBox(width: 16),
          ...List.generate(5 * 2, (index) {
            if (index.isOdd) return const SizedBox(width: 16);
            return _bookCard(_bookImages[index ~/ 2]);
          })
        ],
      ),
    );
  }

  Widget _readTimeCard() {
    return Stack(
      children: [
        Container(
          width: 140,
          height: 100,
          padding: EdgeInsets.only(left: 16),
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8),
            border: Border.all(color: Colors.black12, width: 0.5),
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              const SizedBox(height: 16),
              Text(
                '本周阅读1天',
                style: TextStyle(
                  fontSize: 12,
                  color: Color(0xFFa6906a),
                  fontWeight: FontWeight.w600,
                ),
                textAlign: TextAlign.start,
              ),
              const SizedBox(height: 8),
              Text.rich(TextSpan(
                  style: TextStyle(color: Color(0xFF8e7344), fontWeight: FontWeight.bold),
                  children: [
                    TextSpan(text: '4', style: TextStyle(fontSize: 16)),
                    TextSpan(text: ' '),
                    TextSpan(text: '分钟', style: TextStyle(fontSize: 12)),
                  ]))
            ],
          ),
        ),
        Positioned(
          child: Container(
            padding: EdgeInsets.symmetric(vertical: 8),
            decoration: BoxDecoration(
              gradient: LinearGradient(colors: [
                Color(0xFFe5c999),
                Color(0xFFf9e7c9),
              ]),
              borderRadius: BorderRadius.vertical(bottom: Radius.circular(8)),
            ),
            child: Text(
              '领取1天无限卡',
              textAlign: TextAlign.center,
              style: TextStyle(color: Color(0xFF6a5128), fontSize: 12, fontWeight: FontWeight.w600),
            ),
          ),
          left: 0,
          right: 0,
          bottom: 0,
        ),
      ],
    );
  }

  Widget _bookCard(String image) {
    return Stack(
      children: [
        ClipRRect(
          borderRadius: AppStyle.borderRadius,
          child: Container(
            width: 72,
            height: 100,
            decoration: BoxDecoration(
              color: Colors.green,
            ),
            child: Image.asset(image, fit: BoxFit.fill),
          ),
        ),
      ],
    );
  }
}

/// 推荐
class RecommendView extends StatelessWidget {
  const RecommendView({Key? key, required this.imageList}) : super(key: key);

  final List<String> imageList;

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(16),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            '为你推荐',
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
            textAlign: TextAlign.start,
          ),
          const SizedBox(height: 16),
          GridView.count(
            crossAxisCount: 3,
            childAspectRatio: 0.8,
            physics: const NeverScrollableScrollPhysics(),
            children: imageList.map((e) => CachedNetworkImage(imageUrl: e)).toList(),
            mainAxisSpacing: 16,
            shrinkWrap: true,
          ),
          const SizedBox(height: 16),
          HomePageButton(title: '换一批', onTap: () {}),
        ],
      ),
    );
  }
}

/// 每日福利
class DailyWelfareView extends StatelessWidget {
  const DailyWelfareView({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.symmetric(vertical: 16),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: [
          Text(
            '   每日福利', // 加空格主要是为了省事
            style: TextStyle(fontSize: 24, fontWeight: FontWeight.w600),
            textAlign: TextAlign.start,
          ),
          const SizedBox(height: 16),
          AspectRatio(
            aspectRatio: 16.0 / 9.0,
            // 使用Stack为了让Swiper与文字对齐，但是还是有点问题
            // 其实不使用Swiper比较好，这里只是为了熟悉该控件的用法
            child: Stack(
              fit: StackFit.expand,
              children: [
                Container(),
                Positioned.fill(
                  left: -28,
                  child: Swiper(
                    speed: 400,
                    autoStart: false,
                    circular: false,
                    controller: SwiperController(initialPage: 0),
                    viewportFraction: 0.8,
                    children: List.generate(4, (index) => _welfareCard('$index')),
                  ),
                ),
              ],
            ),
          ),
          Padding(
            padding: const EdgeInsets.all(16),
            child: HomePageButton(title: '进入福利场', onTap: () {}),
          ),
        ],
      ),
    );
  }

  Widget _welfareCard(String image) {
    return Padding(
      padding: EdgeInsets.symmetric(horizontal: 8),
      child: ClipRRect(
        borderRadius: BorderRadius.circular(12),
        child: Container(
          color: Colors.white,
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                height: 120,
                color: Colors.orange,
              ),
              const SizedBox(height: 16),
              Text('    周三读就送$image', style: TextStyle(fontSize: 18)),
              const SizedBox(height: 8),
              Text('    第308期 06.01-06.07', style: TextStyle(color: Colors.black54)),
            ],
          ),
        ),
      ),
    );
  }
}

/// 首页通用按钮
class HomePageButton extends StatelessWidget {
  const HomePageButton({
    Key? key,
    required this.title,
    required this.onTap,
  }) : super(key: key);

  final String title;

  final VoidCallback onTap;

  @override
  Widget build(BuildContext context) {
    return CupertinoButton(
      pressedOpacity: 0.8,
      color: AppColor.appButtonColor,
      child: Text(
        title,
        style: TextStyle(fontSize: 16, fontWeight: FontWeight.w600, color: Colors.black54),
      ),
      onPressed: onTap,
    );
  }
}
